/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved. 
 */
"use strict";
const request = require('request');
const extend = require('extend');
const uuid = require('uuid');
let fs = require('fs');
const api = require('../utils/api');

/**
 * 工具类
 * @type {{send: module.exports.send, dateFormatter: module.exports.dateFormatter, padZero: module.exports.padZero}}
 */
module.exports = {

    /**
     * 发送请求
     * @param param 请求的参数
     * @param callback 回调方法
     */
    send: function (param, callback) {
        if (global.config.mockFlag) {
            //TODO: mock框架的优化
        } else {
            let defaultParam = {
                json: {},
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json",
                    "Accept-Language": param.language || "zh"
                }
            };
            let _param = extend(true, {}, defaultParam, param);
            request(_param, callback);
        }
    },

    /**
     * 深度合并对象
     * @param defaultParam
     * @param myParam
     */
    extend: function (defaultParam, myParam) {
        return extend(true, {}, defaultParam, myParam);
    },

    /**
     * 日期格式化
     * @param date 日期
     * @param format 格式
     * @returns {*} 格式化后的字符串值
     */
    dateFormatter: function (date, format) {
        let o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(),      //day
            "h+": date.getHours(),     //hour
            "m+": date.getMinutes(),   //minute
            "s+": date.getSeconds(),   //second
            "w+": "天一二三四五六".charAt(date.getDay()),   //week
            "q+": Math.floor((date.getMonth() + 3) / 3),  //quarter
            "S": date.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1,
                (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    },

    /**
     * 在指定字符前面补0，以达到指定的长度
     * @param str 需要补0的字符串
     * @param length 需要达到的长度
     * @returns {string} 补0后的字符串
     */
    padZero: function (str, length) {
        let newStr = str + "";
        while (newStr.length < length) {
            newStr = "0" + newStr;
        }
        return newStr;
    },

    /**
     * 本周第一天
     */
    showWeekFirstDay: function (Nowdate, offset) {
        let WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000 - offset * 86400000);
        return global.myUtil.dateFormatter(WeekFirstDay, 'yyyy-MM-dd');
    },
    /**
     * 本周最后一天
     */
    showWeekLastDay: function (Nowdate, offset) {
        let WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000 - offset * 86400000);
        let WeekLastDay = new Date((WeekFirstDay / 1000 + 6 * 86400) * 1000 + 1000 * 60 * 60 * 24);
        return global.myUtil.dateFormatter(WeekLastDay, 'yyyy-MM-dd');
    },
    /**
     * 本月第一天
     */
    showMonthFirstDay: function (Nowdate, offset) {
        let MonthFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth() - offset, 1);
        return global.myUtil.dateFormatter(MonthFirstDay, 'yyyy-MM-dd');
    },
    /**
     * 本月最后一天
     */
    showMonthLastDay: function (Nowdate, offset) {
        let MonthNextFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth() - offset + 1, 1);
        let MonthLastDay = new Date(MonthNextFirstDay - 86400000 + 1000 * 60 * 60 * 24);
        return global.myUtil.dateFormatter(MonthLastDay, 'yyyy-MM-dd');
    },

    /**
     * 获取请求端的类型
     * @param str
     * @returns {string}
     */
    endType: function (str) {
        return /Mobile/.test(str) ? "mobile" : "desktop";
    },

    endTypeEnum: {
        desktop: 1,
        mobile: 3,
        pad: 5
    },

    /**
     * 获取随机串
     */
    uuid: function () {
        return uuid.v4();
    },

    getUserInfo: function (code, callback) {
        global.tool.send({
            method: 'post',
            uri: api.get('756af3ae31a64565a54ec0221f84d377'),
            json: {
                properties: {
                    wechat: code
                }
            }
        }, function (error, response, body) {
            if (body && body.rows.length > 0)
                callback(body.rows[0]);
            else
                callback({status: 0});
        });
    },
    traversalFolderSync : function(folder, param, path, level){
        level = level || 0;
        path = path || [];
        let files = fs.readdirSync(folder);
        files.forEach(function (f, i) {
            path[level] = f;
            let FilePath = folder + '/' + f;
            if(fs.statSync(FilePath).isFile()){
                if(typeof param.each == 'function'){
                    param.each('file', FilePath, path, level);
                }
                if(typeof param.eachFile == 'function'){
                    param.eachFile(FilePath, path, level);
                }
            }else{
                if(typeof param.each == 'function'){
                    param.each('folder', FilePath, path, level);
                }
                if(typeof param.eachFolder == 'function'){
                    param.eachFolder(FilePath, path, level);
                }
                myUtil.traversalFolderSync(FilePath, param, path.concat(), level+1);
            }
        });
        path.shift();
    }
};